package repository

import (
	"context"
	"github.com/ecodeclub/ekit/slice"
	"webook/pkg/logger"
	"webook/search/domain"
	"webook/search/repository/dao"
)

type articleRepository struct {
	dao         dao.ArticleDAO
	tags        dao.TagDAO
	likeInfo    dao.InteractiveLikeDAO
	collectInfo dao.InteractiveCollectDAO
	l           logger.LoggerV1
}

func (a *articleRepository) SearchArticle(ctx context.Context, uid int64, keywords []string) ([]domain.Article, error) {
	artIDs, err := a.tags.Search(ctx, uid, "article", keywords)
	if err != nil {
		return nil, err
	}
	//job17 查询该用户点赞过或收藏过的文章（隐患：如果用户点赞/收藏的文章数量很多 会降低查询速度）
	likeIDs, err := a.likeInfo.Search(ctx, uid, "article")
	if err != nil { //打印日志 不退出 这些策略对用户是无感的
		a.l.Warn("查询用户点赞的文章失败", logger.Error(err), logger.Int64("uid", uid))
	}
	collectIDs, err := a.collectInfo.Search(ctx, uid, "article")
	if err != nil { //打印日志 不退出
		a.l.Warn("查询用户收藏的文章失败", logger.Error(err), logger.Int64("uid", uid))
	}
	arts, err := a.dao.Search(ctx, artIDs, likeIDs, collectIDs, keywords)
	if err != nil {
		return nil, err
	}
	return slice.Map(arts, func(idx int, src dao.Article) domain.Article {
		return domain.Article{
			Id:      src.Id,
			Title:   src.Title,
			Status:  src.Status,
			Content: src.Content,
			Tags:    src.Tags,
		}
	}), nil
}

func (a *articleRepository) InputArticle(ctx context.Context, msg domain.Article) error {
	return a.dao.InputArticle(ctx, dao.Article{
		Id:      msg.Id,
		Title:   msg.Title,
		Status:  msg.Status,
		Content: msg.Content,
	})
}

func NewArticleRepository(d dao.ArticleDAO, td dao.TagDAO) ArticleRepository {
	return &articleRepository{
		dao:  d,
		tags: td,
	}
}
